#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowTitle("串口调试助手(东莞北航研究院)");
    //初始化串口
    mySerialPort=new QSerialPort(this);
    //设置各个串口属性选择栏的默认属性-波特率
    ui->comboBox_baud->setCurrentIndex(7);
    //设置各个串口属性选择栏的默认属性-数据位
    ui->comboBox_data->setCurrentIndex(3);
    //设置各个串口属性选择栏的默认属性-停止位
    ui->comboBox_stop->setCurrentIndex(0);
    //查询可用串口
    findSerialPort();
    //绑定确定事件
    connect(ui->pushButton_confirm,SIGNAL(clicked(bool)),this,SLOT(confirmToSet()));
    //绑定取消事件
    connect(ui->pushButton_cancel,SIGNAL(clicked(bool)),this,SLOT(cancelToSet()));
    //绑定用户复选框事件-波特率
    connect(ui->comboBox_baud,SIGNAL(currentIndexChanged(int)),this,SLOT(setSerialPortSlot()));
    //绑定用户复选框事件-数据位
    connect(ui->comboBox_data,SIGNAL(currentIndexChanged(int)),this,SLOT(setSerialPortSlot()));
    //绑定用户复选框事件-停止位
    connect(ui->comboBox_stop,SIGNAL(currentIndexChanged(int)),this,SLOT(setSerialPortSlot()));
    //用来接收串口信息的槽连接
    connect(mySerialPort,SIGNAL(readyRead()),this,SLOT(processPendingDatagram()));

    QDateTime time = QDateTime::currentDateTime();//获取系统现在的时间
    QString str = time.toString("yyyy-MM-dd hh:mm:ss ddd"); //设置显示格式
    ui->textBrowser_print->append(str);//在标签上显示时间

    recordDialog = new RecordDialog(this);
    recordDialog->hide();

    connect(this,SIGNAL(RecordDataSignal(RecordDataStruct)),recordDialog,SLOT(addTableData(RecordDataStruct)));

    myRecordData.accumTime = 1;
    myRecordData.accumTraffic = 2;
    myRecordData.instantTraffic = 3;
    myRecordData.singleTraffic = 4;

}

/*
 * 设置串口属性
 */
void MainWindow::setSerialPortSlot()
{
    //设置串口号
    mySerialPort->setPortName(ui->comboBox_com->currentText());
    //qDebug()<<mySerialPort->portName();
    //默认8位数据位
    switch (ui->comboBox_data->currentIndex()) {
    case 0:
        mySerialPort->setDataBits(QSerialPort::Data5);
        break;
    case 1:
        mySerialPort->setDataBits(QSerialPort::Data6);
        break;
    case 2:
        mySerialPort->setDataBits(QSerialPort::Data7);
        break;
    case 3:
        mySerialPort->setDataBits(QSerialPort::Data8);
        break;
    default:
        mySerialPort->setDataBits(QSerialPort::Data8);
        break;
    }

    //默认1位停止位
    switch (ui->comboBox_stop->currentIndex()) {
    case 0:
        mySerialPort->setStopBits(QSerialPort::OneStop);
        break;
    case 1:
        mySerialPort->setStopBits(QSerialPort::OneAndHalfStop);
        break;
    case 2:
        mySerialPort->setStopBits(QSerialPort::TwoStop);
        break;
    default:
        mySerialPort->setStopBits(QSerialPort::OneStop);
        break;
    }

    //设置波特率为38400
    switch (ui->comboBox_baud->currentIndex()) {
    case 0:
        mySerialPort->setBaudRate(QSerialPort::Baud1200);
        break;
    case 1:
        mySerialPort->setBaudRate(QSerialPort::Baud2400);
        break;
    case 2:
        mySerialPort->setBaudRate(QSerialPort::Baud4800);
        break;
    case 3:
        mySerialPort->setBaudRate(QSerialPort::Baud9600);
        break;
    case 4:
        mySerialPort->setBaudRate(QSerialPort::Baud19200);
        break;
    case 5:
        mySerialPort->setBaudRate(QSerialPort::Baud38400);
        break;
    case 6:
        mySerialPort->setBaudRate(QSerialPort::Baud57600);
        break;
    case 7:
        mySerialPort->setBaudRate(QSerialPort::Baud115200);
        break;
    default:
        mySerialPort->setBaudRate(QSerialPort::Baud38400);
        break;
    }
}

/*
 * 设置串口号
 */
void MainWindow::setComNum()
{

}

/*
 * 扫描本机当前可用串口
 */
void MainWindow::findSerialPort()
{
    //功能是按顺序遍历可用串口（每找到一个就装载到info中）
    foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
    {
        /*列出每一个可用串口的名字、描述、来源（制造商）
        qDebug() << "Name        : " << info.portName();
        qDebug() << "Description : " << info.description();
        qDebug() << "Manufacturer: " << info.manufacturer();*/
        ui->comboBox_com->addItem(info.portName());
    }
}
void MainWindow::confirmToSet()
{
    setSerialPortSlot();
    //    emit serialPortSignal(mySerialPort,true);

    //先关闭之前打开的串口
    mySerialPort->close();
    //设置串口可读写
    mySerialPort->open(QIODevice::ReadWrite);
    //如果串口初始化成功
    if(mySerialPort->isOpen())
    {
        //设置按钮可选
        setButtonEnable(false);
        //this->setWindowTitle("加入串口成功");
    }
    else
    {
        setButtonEnable(true);
    }
}

void MainWindow::cancelToSet()
{
    setSerialPortSlot();
    //    emit serialPortSignal(mySerialPort,false);
    mySerialPort->close();
    if(!mySerialPort->isOpen())
    {
        setButtonEnable(true);
    }
}


void MainWindow::setButtonEnable(bool flag)
{
    ui->comboBox_baud->setEnabled(flag);
    ui->comboBox_com->setEnabled(flag);
    ui->comboBox_data->setEnabled(flag);
    ui->comboBox_stop->setEnabled(flag);
    ui->pushButton_confirm->setEnabled(flag);
    ui->pushButton_cancel->setEnabled(!flag);
}


MainWindow::~MainWindow()
{
    delete ui;
}


/*
 * 接收串口数据并进行初步处理
 */
void MainWindow::processPendingDatagram()
{
    QByteArray readData;
    QString setBrowserTest="";
    if(mySerialPort->bytesAvailable()>=29)
    {
        //串口读数
        readData = mySerialPort->readAll();
        unsigned char temp[100];
        for(int n=0,m=readData.size();n<m;n++)
        {
            temp[n] =readData[n];
            //        显示接收的数据，用16进制表示
            setBrowserTest = setBrowserTest + QString("%1").arg(temp[n],2,16,QLatin1Char('0')).toUpper()+" ";
            //        将接收文本框的滚动条滑到最下面
            ui->textBrowser_print->moveCursor(QTextCursor::End);
        }
        ui->textBrowser_print->append(setBrowserTest);

        //调用CRC校验和的函数
//        quint32 CRCNum = N_CRC16(temp,27);
        if(CRC[0] == temp[27] && CRC[1] == temp[28])
        {
            //解析数据
            datagramAnalyze(temp);
        }
    }
}

void MainWindow::datagramAnalyze(unsigned char tempData[])
{
    unsigned char temp[4];
    float result[4];
    for(int m = 0;m<4;m++)
    {
        for(int n=0;n<4;n++)
            temp[n] = tempData[n+m*4];
        quint32 data = (temp[0]<<24) + (temp[1]<<16) + (temp[2]<<8) + (temp[3]);
        result[m] = *(float*)&data;
        //        qDebug("result=%f\n",result[m]);
    }
    ui->lineEdit->setText(QString::number(result[0]));
    ui->lineEdit_2->setText(QString::number(result[1]));
    ui->lineEdit_3->setText(QString::number(result[2]));
    ui->lineEdit_4->setText(QString::number(result[3]));
    myRecordData.accumTraffic = result[0];
    myRecordData.instantTraffic = result[1];
    myRecordData.accumTime = result[2];
    myRecordData.singleTraffic = result[3];
}




//CRC校验和，查表法
uchar auchCRCHi[]=
{
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81,
    0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
    0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01,
    0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81,
    0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
    0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01,
    0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81,
    0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
    0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01,
    0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
    0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81,
    0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
    0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01,
    0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81,
    0x40
};

uchar auchCRCLo[] =
{
    0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06, 0x07, 0xC7, 0x05, 0xC5, 0xC4,
    0x04, 0xCC, 0x0C, 0x0D, 0xCD, 0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09,
    0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A, 0x1E, 0xDE, 0xDF, 0x1F, 0xDD,
    0x1D, 0x1C, 0xDC, 0x14, 0xD4, 0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3,
    0x11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44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42, 0x43, 0x83, 0x41, 0x81, 0x80,
    0x40
};

uint MainWindow::N_CRC16(uchar *updata,uint len)
{
    uchar uchCRCHi=0xff;
    uchar uchCRCLo=0xff;
    uint  uindex;
    while(len--)
    {
        uindex=uchCRCHi^*updata++;
        uchCRCHi=uchCRCLo^auchCRCHi[uindex];
        uchCRCLo=auchCRCLo[uindex];
    }
    //高位
    CRC[0] = uchCRCHi;
    //低位
    CRC[1] = uchCRCLo;
    return (uchCRCHi<<8|uchCRCLo);
}

void MainWindow::on_actionHelp_triggered()
{
    QMessageBox box(QMessageBox::Warning,"提示你一下","\n有困难，不会用，找测控组小强去！  \n");
    box.exec();
}

void MainWindow::on_actionVersion_triggered()
{
    QMessageBox box(QMessageBox::Warning,"版本信息","\n2017年05月25日  V1.2.0  \n添加记录功能");
    box.exec();
}

void MainWindow::on_pushButton_RecordTime_clicked()
{
    emit RecordDataSignal(myRecordData);
    recordDialog->show();
}
